<?php
/**
 * User Model
 *
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package models
 */
class User extends AppModel 
{
	/**
    * @var string Model name (faster in PHP 4)
    */
	var $name = 'User';
	
	/**
    * @var string displays field in select box
    */
	var $displayField = 'display';
		
	/**
    * @var array Model behavior
    */			
	var $actsAs = 'ExtendAssociations'; 
	
	/**
    * @var array virtualFields
    */		
	var $virtualFields = array(
		'display' => 'CONCAT(User.name, " [", User.email, "]")'
	);
		
	/**
    * @var array hasAndBelongsToMany relations
    */	
	var $hasAndBelongsToMany = array(
        'Laundry' => array(
            'className' => 'Laundry'
        ),
	);
	
	/**
    * @var array hasAndBelongsToMany relations
    */	
	var $hasOne = array(
        'Password' => array(
            'className' => 'Password'
        ),
	);
	
	/**
    * @var array validation rules
    */		
	var $validate = array( 
		'name' => array(            
			'between' => array(               
				'rule' => array('between', 4, 24),            
				'required' => true,                
				'message' => 'Name must be between 4 and 24 characters long.'            
			),
		),	
		'password' => array(            
			'minLength' => array(               
				'rule' => array('minLength', 6),            
				'required' => true,                
				'message' => 'Minimum 6 characters long.'            
			),
		),	
		'email' => array(            
			'isUnique' => array(               
				'rule' => 'isUnique',                        
				'message' => 'There is already an account on this email address.'      
			),
			'email' => array(               
				'rule' => 'email',                        
				'message' => 'Fill in an valid email address.'      
			),
		),
	);
		
	/**
	 * Function findByLaundryId
	 * 
	 * Find users by a laundry_id
	 * @param integer $id laundry_id
	 * @return array
	 */
	function findByLaundryId($id = null) {
		$users = $this->LaundriesUser->find('all', array(
			'conditions' => array(
				'LaundriesUser.laundry_id' => $id
			)
		));
		foreach($users AS $nr => $relation) {
			unset($users[$nr]);
			$users[] = $relation['LaundriesUser']['user_id'];
		}
		return $users;
	}
	
	/**
	 * Function findLinkedUsersByUserId
	 * 
	 * Find linked users by a user_id
	 * @param integer $id user_id
	 * @return array
	 */
	function findLinkedUsersByUserId($id = null) {
		$users = array();
		foreach($this->Laundry->findByUserId($id) AS $laundry_id) {
			$users = array_merge($users, $this->findByLaundryId($laundry_id));
		}
		return array_unique($users);
	}
}
